/*
 * Licensed to the Tai Ping Jin Ke
 *
 * Copyright (c) 2022 .
 * All rights reserved.
 * 项目名称：太平金科-基础组件封装层-对象存储服务OSS-缺省实现
 * 版权说明：本软件属太平金融科技服务(上海)有限公司所有，在未获得太平金融科技服务(上海)有限公司正式授权情况下，任何企业和个人，不能获取、阅读、安装、传播本软件涉及的任何受知识产权保护的内容。
 */
package com.taipingframework.boot.minio;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.taipingframework.boot.minio.bucket.BucketConstant;
import com.taipingframework.json.JacksonHelper;
import com.taipingframework.utility.constant.SystemConstant;
import com.taipingframework.utility.exception.UtilityException;
import com.taipingframework.utility.extend.ServletHelper;
import io.minio.BucketExistsArgs;
import io.minio.GetObjectArgs;
import io.minio.GetObjectResponse;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.ListObjectsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.Result;
import io.minio.RemoveBucketArgs;
import io.minio.RemoveObjectArgs;
import io.minio.SetBucketPolicyArgs;
import io.minio.StatObjectArgs;
import io.minio.StatObjectResponse;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.MessageFormat;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * MinIO Java SDK is Simple Storage Service (aka S3) client to perform bucket and object operations to any Amazon S3 compatible object storage service.
 */
@Slf4j
@RequiredArgsConstructor
public class ObjectStorageServiceImpl implements ObjectStorageService {

    private final MinioClient minioClient;

    @Override
    public void makeBucket(BucketConstant bucketConstant) throws UtilityException {
        try {
            // 判断存储桶是否存在
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(bucketConstant.bucketName())
                    .build());
            if (bucketExists) {
                log.info("{} exists", bucketConstant.bucketName());
                return;
            }

            // 创建存储桶
            MakeBucketArgs.Builder bucketArgsBuilder = MakeBucketArgs.builder();
            bucketArgsBuilder.bucket(bucketConstant.bucketName());
            if (StringUtils.isNotBlank(bucketConstant.region())) {
                bucketArgsBuilder.region(bucketConstant.region());
            }
            bucketArgsBuilder.objectLock(bucketConstant.objectLock());
            minioClient.makeBucket(bucketArgsBuilder.build());

            // 设置存储桶的策略
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                    .bucket(bucketConstant.bucketName())
                    .config(JacksonHelper.to(bucketConstant.bucketPolicyArgs()))
                    .build());
            log.info("{} is created successfully", bucketConstant.bucketName());
        } catch (Exception e) {
            throw new UtilityException(e);
        }
    }

    @Override
    public void removeBucket(BucketConstant bucketConstant) throws UtilityException {
        try {
            // 判断存储桶是否存在
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(bucketConstant.bucketName())
                    .build());
            if (!bucketExists) {
                log.info("{} does not exist", bucketConstant.bucketName());
                return;
            }

            // 移除存储桶
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketConstant.bucketName())
                    .build());
            log.info("{} is removed successfully", bucketConstant.bucketName());
        } catch (Exception e) {
            throw new UtilityException(e);
        }
    }

    @Override
    public List<Bucket> listBuckets() throws UtilityException {
        try {
            return minioClient.listBuckets();
        } catch (Exception e) {
            throw new UtilityException(e);
        }
    }

    @Override
    public void uploadFileObject(@NonNull InputStream inputStream, String objectName, BucketConstant bucketConstant) throws UtilityException {
        try {
            // 判断存储桶是否存在，存储桶不存在就创建
            this.makeBucket(bucketConstant);

            // 根据文件后缀名获取 content-type
            String mimeType = null;
            Optional<MediaType> mediaTypeOptional = MediaTypeFactory.getMediaType(objectName);
            if (mediaTypeOptional.isPresent()) {
                mimeType = mediaTypeOptional.get().toString();
            }
            if (StringUtils.isEmpty(mimeType)) {
                mimeType = FileUtil.getMimeType(objectName);
            }
            if (StringUtils.isEmpty(mimeType)) {
                mimeType = MediaType.APPLICATION_OCTET_STREAM.toString();
            }

            // 上传文件
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketConstant.bucketName())
                    .object(objectName)
                    .stream(inputStream, inputStream.available(), SystemConstant.DEFAULT_INVALID)
                    .contentType(mimeType)
                    .build());
        } catch (Exception e) {
            throw new UtilityException(e);
        } finally {
            try {
                inputStream.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    @Override
    public String getObjectUrl(String objectName, BucketConstant bucketConstant, @Nullable Method method, @Nullable Duration expiry) throws UtilityException {
        try {
            return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .method(method == null ? Method.GET : method)
                    .bucket(bucketConstant.bucketName())
                    .object(objectName)
                    .expiry(expiry == null ? GetPresignedObjectUrlArgs.DEFAULT_EXPIRY_TIME : (int) expiry.get(ChronoUnit.SECONDS))
                    .build());
        } catch (Exception e) {
            throw new UtilityException(e);
        }
    }

    @Override
    public void removeFileObject(String objectName, BucketConstant bucketConstant) throws UtilityException {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(bucketConstant.bucketName())
                    .object(objectName)
                    .build());
        } catch (Exception e) {
            throw new UtilityException(e);
        }
    }

    @Override
    public List<String> listFileObject(BucketConstant bucketConstant) throws UtilityException {
        try {
            Iterable<Result<Item>> objectResultList = minioClient.listObjects(ListObjectsArgs.builder()
                    .bucket(bucketConstant.bucketName())
                    .build());

            List<String> objectNameList = new ArrayList<>();
            for (Result<Item> objectResult : objectResultList) {
                Item item = objectResult.get();
                objectNameList.add(item.objectName());
            }
            return objectNameList;
        } catch (Exception e) {
            throw new UtilityException(e);
        }
    }

    @Override
    public void downloadFileObject(String objectName, BucketConstant bucketConstant) throws UtilityException {
        try {
            // 获取当前文件的mime-type
            StatObjectResponse statObjectResponse = minioClient.statObject(StatObjectArgs.builder()
                    .bucket(bucketConstant.bucketName())
                    .object(objectName)
                    .build());
            String contentType = statObjectResponse.contentType();

            // 获取当前文件对象的字节流
            GetObjectResponse getObjectResponse = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(bucketConstant.bucketName())
                    .object(objectName)
                    .build());

            HttpServletResponse response = ServletHelper.getResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Accept-Ranges", "bytes"); // 如果存在Accept-Ranges标题，浏览器可能会尝试恢复中断的下载，而不是从头再次开始。
            response.setHeader("Access-Control-Allow-Origin", "*"); // 允许跨域获取请求资源
            response.setHeader("Content-Disposition", MessageFormat.format("attachment; filename=\"{0}\"", objectName));
            response.setContentType(contentType);

            // 将当前文件的字节流写入Servlet响应对象
            IoUtil.copy(getObjectResponse, response.getOutputStream());
        } catch (Exception e) {
            throw new UtilityException(e);
        }
    }

}
